from django.utils.safestring import mark_safe
from django.http.request import QueryDict


class Pagination:

    def __init__(self, page, all_count, params=None, per_num=10, max_show=9):
        try:
            self.page = int(page)
            if self.page <= 0:
                self.page = 1
        except Exception:
            self.page = 1
        # 每页显示的数据条数
        # per_num = 10

        if not params:
            params = QueryDict(mutable=True)
        # {query:123,page:2}
        self.params = params
        """
        1   0   10
        2   10  20   

        """
        # 总数据条数
        all_count = all_count
        # 总页码数
        page_count, more = divmod(all_count, per_num)  # 30 , 0
        if more:
            page_count += 1

        self.page_count = page_count
        # 最多显示页面数
        # max_show = 9
        half_show = max_show // 2

        if page_count < max_show:
            # 总的页码数 < 最多显示页码数
            page_start = 1
            page_end = page_count
        else:
            if self.page - half_show <= 0:
                # 左边极值的情况
                page_start = 1
                page_end = max_show
            elif self.page + half_show >= page_count:

                page_end = page_count
                page_start = page_count - max_show + 1
            else:
                # 页码的起始值
                page_start = self.page - half_show
                # 页码的终止值
                page_end = self.page + half_show

        self.page_start = page_start
        self.page_end = page_end

        # 切片的起始值
        self.start = (self.page - 1) * per_num
        # 切片的终止值
        self.end = self.page * per_num
    @property
    def page_html(self):
        page_list = []

        if self.page == 1:
            page_list.append('<li class="disabled"><a><span aria-hidden="true">&laquo;</span></a></li>')
        else:
            # {query:123,page:2}
            self.params['page'] =self.page-1  #  {query:123,page:1}
            page_list.append(
                '<li> <a href="?{}"><span aria-hidden="true">&laquo;</span></a></li>'.format(self.params.urlencode()))

        for i in range(self.page_start, self.page_end + 1):
            self.params['page'] = i

            if i == self.page:
                page_list.append('<li class="active" ><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))
            else:
                page_list.append('<li><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))

        if self.page >= self.page_count:
            page_list.append('<li class="disabled"><a><span aria-hidden="true">&raquo;</span></a></li>')
        else:
            self.params['page'] = self.page + 1
            page_list.append(
                '<li> <a href="?{}"><span aria-hidden="true">&raquo;</span></a></li>'.format(self.params.urlencode()))

        return mark_safe(''.join(page_list))
